/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.springvision.yuanfeng.device.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.springvision.yuanfeng.device.entity.DeviceSet;
import com.springvision.yuanfeng.device.service.DeviceSetService;

/**
 * 设备告警Controller
 * @author ycb
 * @version 2019-01-11
 */
@Controller
@RequestMapping(value = "${adminPath}/device/deviceSet")
public class DeviceSetController extends BaseController {

	@Autowired
	private DeviceSetService deviceSetService;

	@ModelAttribute
	public DeviceSet get(@RequestParam(required=false) String id) {
		DeviceSet entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = deviceSetService.get(id);
		}
		if (entity == null){
			entity = new DeviceSet();
		}
		return entity;
	}

	/**
	 * 设备告警列表页面
	 */
	@RequiresPermissions("device:deviceSet:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "yuanfeng/device/deviceSetList";
	}

	@ResponseBody
	@RequestMapping(value = "getById")
	public Object getById(String id) {

		DeviceSet deviceSet=new DeviceSet();
		if(StringUtils.isNotEmpty(id)){
			deviceSet=deviceSetService.get(id);

		}
		return deviceSet;
	}

	/**
	 * 设备告警列表数据
	 */
	@ResponseBody
	@RequiresPermissions("device:deviceSet:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(DeviceSet deviceSet, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<DeviceSet> page = deviceSetService.findPage(new Page<DeviceSet>(request, response), deviceSet);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑设备告警表单页面
	 */
	@RequiresPermissions(value={"device:deviceSet:view","device:deviceSet:add","device:deviceSet:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(DeviceSet deviceSet, Model model) {
		model.addAttribute("deviceSet", deviceSet);
		if(StringUtils.isBlank(deviceSet.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		return "yuanfeng/device/deviceSetForm";
	}

	/**
	 * 保存设备告警
	 */
	@RequiresPermissions(value={"device:deviceSet:add","device:deviceSet:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(DeviceSet deviceSet, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, deviceSet)){
			return form(deviceSet, model);
		}
		//新增或编辑表单保存
		deviceSetService.save(deviceSet);//保存
		addMessage(redirectAttributes, "保存设备告警成功");
		return "redirect:"+Global.getAdminPath()+"/device/deviceSet/form?id=1";
	}

	/**
	 * 删除设备告警
	 */
	@ResponseBody
	@RequiresPermissions("device:deviceSet:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(DeviceSet deviceSet, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		deviceSetService.delete(deviceSet);
		j.setMsg("删除设备告警成功");
		return j;
	}

	/**
	 * 批量删除设备告警
	 */
	@ResponseBody
	@RequiresPermissions("device:deviceSet:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			deviceSetService.delete(deviceSetService.get(id));
		}
		j.setMsg("删除设备告警成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("device:deviceSet:export")
	@RequestMapping(value = "export", method=RequestMethod.POST)
	public AjaxJson exportFile(DeviceSet deviceSet, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "设备告警"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			Page<DeviceSet> page = deviceSetService.findPage(new Page<DeviceSet>(request, response, -1), deviceSet);
			new ExportExcel("设备告警", DeviceSet.class).setDataList(page.getList()).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出设备告警记录失败！失败信息："+e.getMessage());
		}
		return j;
	}

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("device:deviceSet:import")
	@RequestMapping(value = "import", method=RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<DeviceSet> list = ei.getDataList(DeviceSet.class);
			for (DeviceSet deviceSet : list){
				try{
					deviceSetService.save(deviceSet);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条设备告警记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条设备告警记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入设备告警失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/device/deviceSet/?repage";
	}

	/**
	 * 下载导入设备告警数据模板
	 */
	@RequiresPermissions("device:deviceSet:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "设备告警数据导入模板.xlsx";
			List<DeviceSet> list = Lists.newArrayList();
			new ExportExcel("设备告警数据", DeviceSet.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/device/deviceSet/?repage";
	}

}